这道题可以和第283题 Remove Zeros 使用同样的思路解决。

解答1[Java] :

class Solution {
    public int removeElement(int[] nums, int val) {
        int i = 0;
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] != val) {
                nums[i] = nums[j];
                i++;
            }
        }
        return i;
    }
}

复杂度分析

时间复杂度:O(n)O(n)

空间复杂度:O(1)O(1)

解答2[Java]:

class Solution {
    public int removeElement(int[] nums, int val) {
        int head = 0;
        int tail = nums.length;
        while (head < tail) {
            if (nums[head] == val) {
                nums[head] = nums[tail - 1];
                tail--;
            } else {
                head++;
            }
        }

        return tail;
    }
}

results matching ""

    No results matching ""